package io.gitee.kotle.android.utils

import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.DialogFragment
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import androidx.lifecycle.lifecycleScope
import kotlinx.coroutines.CoroutineScope

/**
 * dialogFragment show扩展
 * [bundle]传递的参数
 * [tag] tag
 * [uniqueTag] 唯一tag，true，通过这个tag找到实例，则不创建新的对象
 * [newInstanceBlock] 对话框的创建实例
 * [block] 对话框回调，一定是在对话框的onStart回调
 * 返回值：当前对话框，但是生命周期还未走
 */
inline fun <reified T : DialogFragment> FragmentManager.showDialog(
    bundle: Bundle? = null,
    tag: String? = T::class.java.name,
    uniqueTag: Boolean = false,
    newInstanceBlock: (Class<T>) -> T = { T::class.java.newInstance() },
    crossinline block: CoroutineScope.(dialog: T) -> Unit = {}
): T {
    //判断是否只显示一次对话框
    if (uniqueTag) {
        val tagDialog = this.findFragmentByTag(tag)
        if (tagDialog != null && tagDialog is T) {
            tagDialog.lifecycleScope.launchWhenStarted {
                block.invoke(this, tagDialog)
            }
            return tagDialog
        }
    }
    val dialog = newInstanceBlock.invoke(T::class.java)
    if (bundle != null) {
        dialog.arguments = bundle
    }
    dialog.lifecycleScope.launchWhenStarted {
        block.invoke(this, dialog)
    }
    dialog.show(this, tag)
    return dialog
}

/**
 * 在fragment中显示对话框
 */
inline fun <reified T : DialogFragment> Fragment.showDialog(
    bundle: Bundle? = null,
    tag: String? = T::class.java.name,
    uniqueTag: Boolean = false,
    newInstanceBlock: (Class<T>) -> T = { T::class.java.newInstance() },
    crossinline block: CoroutineScope.(dialog: T) -> Unit = {}
): T = childFragmentManager.showDialog(bundle, tag, uniqueTag, newInstanceBlock, block)


/**
 * 在AppCompatActivity中显示对话框
 */
inline fun <reified T : DialogFragment> AppCompatActivity.showDialog(
    bundle: Bundle? = null,
    tag: String? = T::class.java.name,
    uniqueTag: Boolean = false,
    newInstanceBlock: (Class<T>) -> T = { T::class.java.newInstance() },
    crossinline block: CoroutineScope.(dialog: T) -> Unit = {}
): T = supportFragmentManager.showDialog(bundle, tag, uniqueTag, newInstanceBlock, block)



